# coding=UTF-8
import os
import time

from database.mapper import boards_info, stock_info
from service import get_a_stock_info
from utils import date_util, parse_util, http_util

base_path = os.path.join(os.getcwd().split('StockMonitor')[0] + 'StockMonitor')

# 获取东方财富所有的板块信息
url1 = 'http://quote.eastmoney.com/center/api/sidemenu.json'  # 2021-07-12


def get_detail_stock(code):
    time_stamp = int(round(time.time() * 1000))
    url_i = 'http://push2.eastmoney.com/api/qt/clist/get?ut=bd1d9ddb04089700cf9c27f6f7426281&pi=0&pz=8&po=1&fid=f62&fs=b:' + code + \
            '&=&fields=f1,f2,f12,f13,f14,f62,f152,f128,f3,f62,f184,f66,f69,f72,f75,f78,f81,f84,f87' \
            '&cb=jQuery1124013032222692515671_' + str(time_stamp) + '&_=' + str(time_stamp + 127)
    # resp = requests.get(url_i)
    # data = eval(str(resp.content.decode('utf-8')).split('(')[1].split(')')[0].replace('null', '""'))['data']
    resp_content = str(http_util.request_get(url_i).content.decode('utf-8'))
    data = eval(resp_content[resp_content.find('(') + 1:resp_content.rfind(')')].replace('null', '""'))['data']
    total = int(data['total'])
    if total == 0:
        return
    stock_dict = data['diff']
    for rank in stock_dict:
        # 只有8枚
        print(stock_dict[rank])


def get_all_stock_info(code):
    time_stamp = int(round(time.time() * 1000))
    # 获取全部信息
    plate_stock_list = []
    for i in range(1, 100):
        url_ii = 'http://push2.eastmoney.com/api/qt/clist/get?pn=' + str(i) + \
                 '&pz=50&po=1&np=1&ut=b2884a393a59ad64002292a3e90d46a5&fltt=2&invt=2&fid=f62&fs=b:' + code + \
                 '&stat=1&fields=f12,f14,f2,f3,f62,f184,f66,f69,f72,f75,f78,f81,f84,f87,f204,f205,f124&' \
                 'rt=53145555&cb=jQuery18305251896309956461_' + str(time_stamp) + '&_=' + str(time_stamp + 127)
        data_str = ''
        try:
            # resp_ii = requests.get(url_ii)
            # data_str = str(resp_ii.content.decode('utf-8')).split('(')[1].split(')')[0].replace('null', '""')
            resp_content = str(http_util.request_get(url_ii).content.decode('utf-8'))
            data_str = resp_content[resp_content.find('(') + 1:resp_content.rfind(')')].replace('null', '""')
        except Exception as e:
            print(url_ii)
            print('Error:', e)
        # finally:
        #     print('')
        data = eval(data_str)['data']
        if data == '':
            break
        total = int(data['total'])
        if total == 0:
            break
        stock_list = data['diff']
        for stock_info in stock_list:
            plate_stock_list.append(stock_info)
        return plate_stock_list


def get_all_paltes_info():
    # resp1 = requests.get(url1)
    resp1 = http_util.request_get(url1)
    resp1_content = str(resp1.content.decode('utf-8').replace('true', '1').replace('false', '0'))
    plate_list = eval(resp1_content)
    s_dict = parse_util.list_to_dict(stock_info.selectall(), 'code')
    for plate_one in plate_list:
        title = plate_one['title']
        key = plate_one['key']
        flag = 0
        if key == 'hsbroad':
            next = plate_one['next']
            for plate_two in next:
                title_two = plate_two['title']
                key_two = plate_two['key']
                next_two = plate_two['next']
                for plate_thr in next_two:
                    title_thr = plate_thr['title']
                    key_thr = plate_thr['key'].split('.')[1]
                    res = boards_info.select_board_one(key_thr)
                    if not res or date_util.diff_days(res['up_time'], date_util.get_date_time()) >= 3:
                        try:
                            boards_info.delete_board(key_thr)
                            plate_stock_list = get_all_stock_info(key_thr)
                            data_list = []
                            for stock in plate_stock_list:
                                if not s_dict.get(stock['f12']):
                                    if stock['f12'][0] == '2' or stock['f12'][0] == '9':
                                        print('不考虑' + stock['f12'])
                                        continue
                                    get_a_stock_info.add_a_stock(stock['f12'])
                                    s_dict = parse_util.list_to_dict(stock_info.selectall(), 'code')
                                    if not s_dict.get(stock['f12']):
                                        break
                                data_list.append({'code': stock['f12'], 'name': stock['f14'],
                                                  'total_val': s_dict.get(stock['f12'])['total_val'],
                                                  'platform': 'dfcf', 'board_code': key_thr, 'board_one': title_thr,
                                                  'board_two': title_two, 'board_thr': title})
                            boards_info.insert_mul(data_list)
                        except:
                            print('刷新板块error,' + str(key_thr))


if __name__ == '__main__':
    print("start")
    # get_all_stock_info('600031')
    get_all_paltes_info()
